using System;
using Gnome;
using Gtk;

namespace TVListings
{
	public class PanelAppletClass : Gnome.PanelApplet
	{
		protected PanelAppletClass(IntPtr raw) : base (raw) {}
		protected TVGuide Guide;
		protected AppletWindow AppletWindow = null;

		static void Main (string[] argv)
		{
			Gnome.Program p = new Gnome.Program("TVApplet", "0.1", Gnome.Modules.UI, argv);
			PanelAppletFactory.Register(typeof(PanelAppletClass));
		}

		public override void Creation()
		{
			/// TODO: Get an icon and use a better path
			Gdk.Pixbuf p = new Gdk.Pixbuf("/usr/share/icons/hicolor/scalable/apps/ontv.svg");
			Image Icon = new Image(p.ScaleSimple((int)this.Size, (int)this.Size, Gdk.InterpType.Hyper));
			EventBox e = new EventBox();
			e.Add(Icon);
			e.ButtonPressEvent += new ButtonPressEventHandler(OnIconClick);
			this.Add(e);
			this.ShowAll();
			
			this.MoveFocusOutOfApplet += OnMoveFocusOutOfApplet;
			
			string xml = "<popup name=\"button3\"><menuitem name=\"Update\" verb=\"UpdateListings\" _label=\"_Update Listings\" pixtype=\"stock\" pixname=\"gtk-refresh\"/></popup>";
			this.SetupMenu(xml, new BonoboUIVerb[] { new BonoboUIVerb("UpdateListings", new ContextMenuItemCallback(UpdateListings)) });
			
			/// TODO: Store in a settings file
			Guide = TVGuide.FromFile("/home/chrisost/.xmltv/tv_grab_na_dd.xmltv");
			this.AppletWindow = new AppletWindow();
			this.AppletWindow.Hide();
			this.AppletWindow.Guide = Guide;
		}

		void UpdateListings()
		{
			/// TODO: Implement update listings
		}

		protected void OnIconClick(object sender, ButtonPressEventArgs e)
		{
			if (e.Event.Button != 1)
				return; // Only want left click

			if (!(ShowWindow() || HideWindow()));			
		}
		
		protected void OnMoveFocusOutOfApplet(object sender, MoveFocusOutOfAppletArgs e)
		{
			HideWindow();
		}
		
		bool ShowWindow()
		{
			if (this.AppletWindow.Visible)
				return false;

			int x, y, w, h;
			this.GdkWindow.GetOrigin(out x, out y);
			this.AppletWindow.GetSize(out w, out h);
			this.AppletWindow.Move(x + (int)this.Size - w, y + (int)this.Size);
			this.AppletWindow.ShowAll();
			this.State = Gtk.StateType.Selected;
			return true;		
		}
		
		bool HideWindow()
		{
			if (!this.AppletWindow.Visible)
				return false;

			this.AppletWindow.Hide();
			this.State = Gtk.StateType.Normal;
			return true;
		}

		public override string IID {
			get { return "OAFIID:TVApplet"; }
		}

		public override string FactoryIID {
			get { return "OAFIID:TVApplet_Factory"; }
		}
	}
}